// 确保在DOM加载完成后执行Vue应用初始化
document.addEventListener('DOMContentLoaded', () => {
    const { createApp } = Vue;
    
    createApp({
        data() {
            return {
                // 分类相关
                categories: [],
                // 历史记录相关
                historyRecords: [],
                historyLoading: false,
                historyTotalCount: 0,
                historyCurrentPage: 1,
                historyPageSize: 10,
                historyFilter: {
                    type: '',
                    category: '',
                    startDate: '',
                    endDate: ''
                },
                // 错误处理
                showError: false,
                errorMessage: '',
                // 移动端菜单
                mobileMenuOpen: false
            }
        },
        
        methods: {
            // 加载分类列表
            loadCategories() {
                fetch('/get_category')
                    .then(response => response.json())
                    .then(data => {
                        if (data.success && data.category_list) {
                            this.categories = data.category_list;
                        }
                    })
                    .catch(error => {
                        console.error('加载分类列表失败:', error);
                        this.showError = true;
                        this.errorMessage = '加载分类列表失败，请稍后重试';
                    });
            },
            
            // 加载历史记录
            loadHistory() {
                this.historyLoading = true;
                this.historyRecords = [];
                
                const params = {
                    page: this.historyCurrentPage,
                    page_size: this.historyPageSize,
                    upload_type: this.historyFilter.type,
                    category: this.historyFilter.category,
                    start_date: this.historyFilter.startDate,
                    end_date: this.historyFilter.endDate
                };
                
                // 移除空值参数
                Object.keys(params).forEach(key => {
                    if (params[key] === null || params[key] === undefined || params[key] === '') {
                        delete params[key];
                    }
                });
                
                const queryString = new URLSearchParams(params).toString();
                
                fetch(`/history/upload?${queryString}`)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('获取历史记录失败');
                        }
                        return response.json();
                    })
                    .then(data => {
                        this.historyRecords = data.records || [];
                        this.historyTotalCount = data.total_count || 0;
                    })
                    .catch(error => {
                        console.error('获取历史记录错误:', error);
                        this.showError = true;
                        this.errorMessage = '获取历史记录失败，请稍后重试';
                    })
                    .finally(() => {
                        this.historyLoading = false;
                    });
            },
            
            // 跳转到指定历史记录页面
            goToHistoryPage(page) {
                if (page < 1 || page > this.historyTotalPages) {
                    return;
                }
                this.historyCurrentPage = page;
                this.loadHistory();
            },
            
            // 查看历史记录详情
            viewRecordDetails(record) {
                console.log('查看记录详情:', record);
                // 显示详情弹窗
                let statusText = '未知状态';
                if (record.files_info && record.files_info.every(f => f.success)) {
                    statusText = '全部成功';
                } else if (record.files_info && record.files_info.some(f => f.success)) {
                    statusText = '部分成功';
                } else {
                    statusText = '失败';
                }
                
                let fileDetails = '无文件信息';
                if (record.files_info && record.files_info.length > 0) {
                    fileDetails = record.files_info.map(file => {
                        const name = file.original_filename || file.original_url || '未知文件';
                        const status = file.success ? '成功' : '失败';
                        const error = file.error ? ` - 错误: ${file.error}` : '';
                        return `${name} - ${status}${error}`;
                    }).join('\n');
                }
                
                alert(`记录ID: ${record.id || '未知'}\n类型: ${record.upload_type || '未知'}\n分类: ${record.category || '未分类'}\n上传时间: ${this.formatDate(record.timestamp)}\n状态: ${statusText}\n\n文件详情:\n${fileDetails}`);
            },
            
            // 格式化日期
            formatDate(timestamp) {
                if (!timestamp) return '未知时间';
                
                const date = new Date(timestamp);
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');
                
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            },
            
            // 切换移动端菜单
            toggleMobileMenu() {
                this.mobileMenuOpen = !this.mobileMenuOpen;
            },
            
            // 关闭错误提示
            closeError() {
                this.showError = false;
                this.errorMessage = '';
            }
        },
        
        // 计算属性
        computed: {
            // 历史记录总页数
            historyTotalPages() {
                return Math.max(1, Math.ceil(this.historyTotalCount / this.historyPageSize));
            },
            
            // 当前页起始记录
            historyCurrentPageStart() {
                return Math.max(1, (this.historyCurrentPage - 1) * this.historyPageSize + 1);
            },
            
            // 当前页结束记录
            historyCurrentPageEnd() {
                return Math.min(this.historyTotalCount, this.historyCurrentPage * this.historyPageSize);
            }
        },
        
        // 生命周期钩子
        mounted() {
            // 加载分类列表
            this.loadCategories();
            
            // 加载历史记录
            this.loadHistory();
            
            // 监听窗口滚动，关闭移动端菜单
            window.addEventListener('scroll', () => {
                if (this.mobileMenuOpen) {
                    this.mobileMenuOpen = false;
                }
            });
        }
    }).mount('body');
});